package com.dotmedia.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class MacroFieldsServlet
 */
public class MacroFieldsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger("dotmedia.servlets");

	private static final String HTML_RESPONSE_TYPE = "text/html";
	private static final String TEMPLATE_CODE_PARAMETER = "templateCode";
	private static final String COMMA_DELIMITER = ",";
	private static final String COLON_DELIMITER = ":";
	private static final String DOLLAR_SYMBOL = "$";
	private static final String OPEN_BRACE = "{";
	private static final String CLOSE_BRACE = "}";

	// types of macros
	private static final String NUMERIC = "numeric";
	private static final String GENERAL_UPLOAD = "genupload";
	private static final String SWF_UPLOAD = "swfupload";
	private static final String IMAGE_UPLOAD = "imgupload";
	private static final String DIMAGE_UPLOAD = "dimgupload";
	private static final String TEXT = "text";
	private static final String HTML = "html";
	private static final String LIST = "list";
	private static final String URL = "url";

	public MacroFieldsServlet() {
		super();
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// here we will generate the macro fields which will be sent back to the client when the code of the template is changed
		logger.info("IN servlet MacroFieldsServlet");
		response.setContentType(HTML_RESPONSE_TYPE);
		String templateCode = request.getParameter(TEMPLATE_CODE_PARAMETER);
		logger.info("Template code received=" + templateCode);
		String htmlCode = getMacroFieldsHtml(templateCode);
		response.getOutputStream().println(htmlCode);
		logger.info("OUT servlet MacroFieldsServlet");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	/**
	 * This method gets the html macro code for the templates
	 * 
	 * @param templateCode
	 * @return
	 */
	public String getMacroFieldsHtml(String templateCode) {
		logger.info("IN method getMacroFieldsHtml() in servlet MacroFieldsServlet");
		String htmlCode = "";
		// This is a template code with a numeric macro with a predefined value ${numeric,name1,1}, 3 uploads ${genupload,name2}, ${swfupload,name3},
		// ${imgupload,name4}, ${dimgupload,name5}, a text ${text,name6}, a html ${html,name7},
		// ${list,name8,[allowedValue1:label1,allowedValue2:label2]}
		int startDollarIndex = templateCode.indexOf(DOLLAR_SYMBOL);
		templateCode = templateCode.substring(startDollarIndex); // this is to be processed
		String[] individualMacros = templateCode.split("},");
		for (int index = 0; index < individualMacros.length; index++) {
			// trimmimg all the macro strings
			String currentMacroString = individualMacros[index];
			currentMacroString = currentMacroString.trim();
			if (!currentMacroString.endsWith(CLOSE_BRACE)) {
				currentMacroString += CLOSE_BRACE;
			}
			int beginIndex = currentMacroString.indexOf(DOLLAR_SYMBOL);
			int endIndex = currentMacroString.lastIndexOf(CLOSE_BRACE);
			currentMacroString = currentMacroString.substring(beginIndex, endIndex + 1);
			individualMacros[index] = currentMacroString;
		}
		// remove identical entries from the macros list
		// TODO: siddharthsaha - write code for removing identical entries from the macro list
		// now we will generate the html for individual macros
		int tdCriteria = 1;
		htmlCode += "<table name = 'addNewAdMacroTable' id = 'addNewAdMacroTable' class = 'mt_table'>";
		for (String currentMacroString : individualMacros) {
			int openingBraceStartIndex = currentMacroString.indexOf(OPEN_BRACE);
			int closingBraceEndIndex = currentMacroString.lastIndexOf(CLOSE_BRACE);
			currentMacroString = currentMacroString.substring(openingBraceStartIndex + 1, closingBraceEndIndex);
			String[] splittedCurrentMacroString = currentMacroString.split(COMMA_DELIMITER);
			for (int index = 0; index < splittedCurrentMacroString.length; index++) {
				// trimming individual strings
				splittedCurrentMacroString[index] = splittedCurrentMacroString[index].trim();
			}
			// now we have to generate the code for this macro
			String typeOfMacro = splittedCurrentMacroString[0];
			String nameOfMacro = splittedCurrentMacroString[1];
			String valueOfMacro = null;
			if (splittedCurrentMacroString.length > 2) {
				valueOfMacro = "";
				for (int valueIndex = 2; valueIndex < splittedCurrentMacroString.length; valueIndex++) {
					valueOfMacro += splittedCurrentMacroString[valueIndex];
					if (valueIndex != (splittedCurrentMacroString.length - 1)) {
						valueOfMacro += COMMA_DELIMITER;
					}
				}
			}
			if (typeOfMacro.equals(NUMERIC)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"text\" name = \"numeric_" + nameOfMacro + "\" id = \"numeric_" + nameOfMacro + "\" style='width: 100%'";
				if (valueOfMacro != null) {
					htmlCode += "value = \"" + valueOfMacro + "\"";
				}
				htmlCode += " /> </td></tr>";
			} else if (typeOfMacro.equals(URL)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"text\" name = \"url_" + nameOfMacro + "\" id = \"url_" + nameOfMacro + "\" style='width: 100%'";
				if (valueOfMacro != null) {
					htmlCode += "value =\"" + valueOfMacro + "\"";
				}
				htmlCode += " /> </td></tr>";
			} else if (typeOfMacro.equals(GENERAL_UPLOAD)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"file\" name = \"genupload_" + nameOfMacro + "\" id = \"genupload_" + nameOfMacro
						+ "\" style='width: 100%'/> </td></tr>";
			} else if (typeOfMacro.equals(SWF_UPLOAD)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"file\" name = \"swfupload_" + nameOfMacro + "\" id = \"swfupload_" + nameOfMacro
						+ "\" style='width: 100%'/> </td></tr>";
			} else if (typeOfMacro.equals(IMAGE_UPLOAD)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"file\" name = \"imgupload_" + nameOfMacro + "\" id = \"imgupload_" + nameOfMacro
						+ "\" style='width: 100%'/> </td></tr>";
			} else if (typeOfMacro.equals(DIMAGE_UPLOAD)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<input type = \"file\" name = \"dimgupload_" + nameOfMacro + "\" id = \"dimgupload_" + nameOfMacro
						+ "\" style='width: 100%'/> </td></tr>";
			} else if (typeOfMacro.equals(TEXT)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<textarea name = \"text_" + nameOfMacro + "\" style='width: 100%'>";
				if (valueOfMacro != null) {
					htmlCode += valueOfMacro;
				}
				htmlCode += "</textarea></td></tr>";
			} else if (typeOfMacro.equals(HTML)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
					logger.info("nameOfMacro: " + nameOfMacro);
					logger.info("HtmlCode: " + htmlCode);
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<textarea name = \"html_" + nameOfMacro + "\" id =\"html_" + nameOfMacro
						+ "\" class = \"mceEditor\"></textarea></td></tr>";
			} else if (typeOfMacro.equals(LIST)) {
				tdCriteria++;
				if ((tdCriteria % 2) == 0) {
					htmlCode += "<tr class = 'even_td'><td>" + nameOfMacro + ":</td><td>";
				} else {
					htmlCode += "<tr class = 'odd_td'><td>" + nameOfMacro + ":</td><td>";
				}
				htmlCode += "<select name=\"list_" + nameOfMacro + "\" id = \"list_" + nameOfMacro + "\" style='width: 100%'>";
				if (valueOfMacro != null) {
					valueOfMacro = valueOfMacro.substring(1, valueOfMacro.length() - 2);
					String[] values = valueOfMacro.split(COMMA_DELIMITER);
					for (String currentValue : values) {
						currentValue = currentValue.trim();
						String[] currentValueAndLabelSplitted = currentValue.split(COLON_DELIMITER);
						htmlCode += "<option value = \"" + currentValueAndLabelSplitted[0].trim() + "\">" + currentValueAndLabelSplitted[1].trim()
								+ "</option>";
					}
				}
				htmlCode += "</select></td></tr>";
			}
		}
		htmlCode += "</table>";
		logger.info("OUT method getMacroFieldsHtml() in servlet MacroFieldsServlet");
		return htmlCode;
	}

}
